package com.heima.comment.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.comment.service.CommentHotService;
import com.heima.comment.service.CommentService;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentDTO;
import com.heima.model.comment.dtos.CommentLikeDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.vo.ApCommentVo;
import com.heima.model.common.constants.article.HotArticleConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class Commentimpl implements CommentService {

    @Autowired
    private UserFeign userFeign;


    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private CommentHotService commentHotService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Override
    public ResponseResult saveComment(CommentSaveDTO dto) {
        //校验参数
        //校验是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        //远程查询当前登陆用户信息
        ResponseResult<ApUser> userById = userFeign.findUserById(user.getId());
        //检查远程调用是否出现异常
        if (!userById.checkCode()) {
            //返回前端远程调用失败
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        //获取远程调用中的数据(此时为apuser类型)
        ApUser data = userById.getData();
        if (data == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "当前用户不存在");
        }

        //创建评论信息,并保存到mongo
        ApComment apComment = new ApComment();
        apComment.setAuthorId(user.getId());
        apComment.setAuthorName(user.getName());
        apComment.setArticleId(dto.getArticleId());
        apComment.setType((short) 0);
        apComment.setImage(data.getImage());
        apComment.setAuthorName(data.getName());
        apComment.setContent(dto.getContent());
        apComment.setLikes(0);
        apComment.setReply(0);
        apComment.setFlag((short) 0);
        apComment.setCreatedTime(new Date());
        apComment.setUpdatedTime(new Date());
        mongoTemplate.insert(apComment);

        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.COMMENT);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("评论行为 发送消息 ==>{}",mess);


        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult like(CommentLikeDTO dto) {
        //参数校验
        //评论id不能为空  operation必须为 0  或  1
        //根据评论id查询评论数据， 为返回错误信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }

        Map map = new HashMap<>();

        ApComment byId = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (byId == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "评论不存在");
        }
        //如果是点赞操作 判断是否已经点赞

        if (dto.getOperation().intValue() == 0) {
            //点赞
            //点过赞提示 请勿重复点赞
            Query query = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentId").is(byId.getId())
                    .and("operation").is((short) 0));
            ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);
            if (one != null) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "请勿重复点赞");
            }
            //未点过赞   保存点赞信息到mongo
            ApCommentLike like = new ApCommentLike();
            like.setAuthorId(user.getId());
            like.setCommentId(byId.getId());
            like.setOperation((short) 0);
            mongoTemplate.insert(like);
            //并修改评论信息的点赞数量( + 1)
            byId.setLikes(byId.getLikes() + 1);
            mongoTemplate.save(byId);
            map.put("likes", byId.getLikes());
            commentHotService.hotCommentExecutor(byId);
        } else {
            //如果是取消点赞操作
            //删除点赞信息
            Query query = Query.query(Criteria.where("authorId").is(user.getId())
                    .and("commentId").is(byId.getId())
                    .and("operation").is((short) 0));
            mongoTemplate.remove(query, ApCommentLike.class);
            //  并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
            byId.setLikes(byId.getLikes() - 1);
            if (byId.getLikes() < 0) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);
            }
            mongoTemplate.save(byId);
            map.put("likes", byId.getLikes());
        }

        //返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult findByArticleId(CommentDTO dto) {
        //校验文章id
        //
        //校验size
        if (dto.getSize() == null || dto.getSize() <= 0) {
            dto.setSize(10);
        }
        //根据条件查询评论列表
        //
        //(文章id  , 创建时间 小于最小时间 , 截取size条记录 , 创建时间降序)
        //定义集合
        List<ApComment> apCommentList = null;
        //判断是否是首页
        if (dto.getIndex().intValue() == 1) {
            //如果是根据id查询,查询所有
            Query with = Query.query(Criteria.where("articleId").is(dto.getArticleId())

                            .and("flag").is((short) 1)).limit(5)
                    .with(Sort.by(Sort.Order.desc("likes")));
            apCommentList = mongoTemplate.find(with, ApComment.class);

            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("createdTime").lt(dto.getMinDate())
                    .and("flag").is((short) 0));
            query.with(Sort.by(Sort.Order.desc("createdTime")));
            query.limit(dto.getSize() - apCommentList.size());
            List<ApComment> list = mongoTemplate.find(query, ApComment.class);
            apCommentList.addAll(list);
            //判断当前用户是否登录
            ApUser user = AppThreadLocalUtils.getUser();
            if (user == null) {
                //如果未登录直接返回评论列表
                return ResponseResult.okResult(apCommentList);
            }
            List<ApCommentVo> apCommentVos = new ArrayList<>();
            for (ApComment apComment : apCommentList) {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(apComment, apCommentVo);
                Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId())
                        .and("authorId").is(user.getId())
                        .and("operation").is((short) 0));
                ApCommentLike one = mongoTemplate.findOne(query1, ApCommentLike.class);
                if (one != null) {
                    apCommentVo.setOperation((short) 0);
                }
                apCommentVos.add(apCommentVo);
            }
            return ResponseResult.okResult(apCommentVos);

        } else {
            Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId())
                    .and("createdTime").lt(dto.getMinDate()).and("flag").is((short) 0)
            );
            query.with(Sort.by(Sort.Order.desc("createdTime")));
            query.limit(dto.getSize());
            apCommentList = mongoTemplate.find(query, ApComment.class);
            //判断当前用户是否登录
            ApUser user = AppThreadLocalUtils.getUser();
            if (user == null) {
                //如果未登录直接返回评论列表

                return ResponseResult.okResult(apCommentList);
            }
            //如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
            // (将所有ApComment 转成 ApCommentVO , 点过赞的operation设置为0)
            //5.1 根据当前列表中评论id  和  登录人id 查询评论点赞表，得到点赞数据
            //遍历评论列表
            //将每一个评论  ApComment 转成 ApCommentVO
            //其中  如果当前评论id在点赞记录中存在  设置operation字段为0  不存在不用做任何处理
            List<ApCommentVo> apCommentVos = new ArrayList<>();
            for (ApComment apComment : apCommentList) {
                ApCommentVo apCommentVo = new ApCommentVo();
                BeanUtils.copyProperties(apComment, apCommentVo);
                Query query1 = Query.query(Criteria.where("commentId").is(apComment.getId())
                        .and("authorId").is(user.getId())
                        .and("operation").is((short) 0));
                ApCommentLike one = mongoTemplate.findOne(query1, ApCommentLike.class);
                if (one != null) {
                    apCommentVo.setOperation((short) 0);
                }
                apCommentVos.add(apCommentVo);
            }
            return ResponseResult.okResult(apCommentVos);
        }
    }
}
